import styles from './index.less'
import React, { Fragment, Component } from 'react'
import { Prompt } from 'react-router-dom'

import { formatMessage } from 'umi-plugin-locale';   //用于多语言切换
import { connect } from 'dva';
import LeftSider from '@/components/LeftSider'
import VideoPlayer from '@/components/VideoPlayer'
import BizIcon from '@/components/BizIcon'
import screenCount from '@/utils/screenCount'
import { Tooltip, Modal, message } from 'antd';
import { removeArray } from '@/utils/utils';
import { hasFullScreenElement, setFullScreen, exitFullScreen } from '@/utils/utils'
import { closeLiveVideo } from '@/services/device';

@connect(({ device, config, loading }) => ({
  device,
  config,
  loading: loading.models.device,
}))

class LiveVideo extends Component {
  state = {
    screenIndex: 3,
    playList: [],
    list: [],
    loadError: false,
    sosList: []
  }

  constructor(props) {
    super(props)
    this.nextGuid = 0;
    this.deletePlayer = this.deletePlayer.bind(this);
  }

  changeVideoCount(index) {
    this.setState({
      screenIndex: index
    })
  }
  sosTimer = null
  componentDidMount() {
    // 临时解决方案
    // 获取SOS报警的设备
    this.sosTimer = setInterval(() => {
      if (window.sosList != undefined) {
        window.sosList.forEach(gbId => {
          if ((this.state.playList.findIndex(item => item.gbId === gbId) === -1)) {
            this.fetchDeviceInfoByGBID(gbId)
          }
        });
      }
    }, 1000)

    this.props.dispatch({
      type: 'config/fetch',
      callback: (res) => {
        this.setState({
          screenIndex: res.videoCount || this.state.screenIndex
        })
      }
    })

    if (window.LoadVideoError === true) {
      this.setState({ loadError: true })
    }

    window.onbeforeunload = e => {
      this.closeLiveVideo()
    }

  }

  closeLiveVideo = async () => {
    let ids = this.state.playList.map(item => {
      return item.id
    })
    ids.length && this.props.dispatch({
      type: 'device/closeLiveVideo',
      payload: { 'ids[]': ids },
    })

  }

  componentWillUnmount() {
    clearInterval(this.sosTimer)
  }

  componentDidUpdate() {

  }

  onSelect(selectedKeys) {
    // console.log(selectedKeys)
  }

  onDoubleClick(selectedKeys) {
    if (this.state.loadError) {
      Modal.error({
        content: '视频播放组件加载失败'
      })
      return;
    }
    this.fetchDeviceInfoById(selectedKeys)
  }

  onCheck(selectedNodes) {

    if (selectedNodes.length > 0) {

      // 播放列表中的key
      let playList = this.state.playList.map(({ id }) => {
        return id
      })

      // 已选中的keys
      let selectedKeys = selectedNodes.map(({ key }) => {
        return key
      })

      // 取 播放列表和选中的key 的并集
      let unionKey = playList.concat(selectedKeys.filter(val => { return !(playList.indexOf(val) > -1) }))

      // 取 选中的key和全部并集中的差集
      let diff = unionKey.filter(function (val) { return selectedKeys.indexOf(val) === -1 })

      // 如果存在差集
      if (diff.length > 0) {
        diff.forEach(val => {
          let playListItem = this.state.playList.filter(item => {
            return item.id == val
          })

          if (playListItem[0]) {
            this.deletePlayer(playListItem[0].gbId)
          }

        })
      } else {
        selectedNodes.forEach(({ key }) => {
          this.fetchDeviceInfoById(key)
        })
      }

    } else {
      this.setState({ playList: [] })
    }

  }



  
  flatten = (list = []) => {
    const transferDataSource = [];
    const loop = (list = []) => {
      list.forEach(item => {
          let newItem = {
              ...item,
              key: item.sn || item.key
          }
          item.type === 1 && transferDataSource.push(newItem);
          loop(item.children);
      });
    }
    loop(list)
    return transferDataSource
  }

  onFresh = (data) => {
    let deviceList = this.flatten(data);
    // console.log(deviceList)
  }

  fetchDeviceInfoById(id) {
    this.props.dispatch({
      type: 'device/fetchDeviceInfo',
      payload: {
        id: id,
        from: 'video'
      },
      callback: ({ data }) => {
        if (data.isOnline === 0) {
          Modal.warning({
            content: formatMessage({ 'id': 'device.offline' })
          })
        } else if (data.isStreamOnline === 0) {
          Modal.warning({
            content: formatMessage({ 'id': 'device.streamOffline' })
          })
        } else if (data.isDisabled === 1) {
          Modal.warning({
            content: formatMessage({ 'id': 'device.disabled' })
          })
        } else {
          if (data.gbId !== '') {
            this.addToPlayList(data)
          } else {
            Modal.error({
              content: formatMessage({ 'id': 'device.gbidIsNull' })
            })
          }
        }

      }
    })
  }

  fetchDeviceInfoByGBID(gbId) {
    this.props.dispatch({
      type: 'device/fetchDeviceInfo',
      payload: {
        gbId: gbId,
        sn: '00000000000000'
      },
      callback: res => {
        let data = res.data

        if (data.isOnline === 0) {
          window.sosList = removeArray(window.sosList, gbId)
          Modal.warning({
            content: formatMessage({ 'id': 'device.offline' })
          })
        } else if (data.isDisabled === 1) {
          window.sosList = removeArray(window.sosList, gbId)
          Modal.warning({
            content: formatMessage({ 'id': 'device.disabled' })
          })
        } else {
          let newData = Object.assign({ isSos: true }, data)
          // 是否是SOS 过来的 
          if (newData.gbId !== '') {
            this.addToPlayList(newData)
          } else {
            Modal.error({
              content: formatMessage({ 'id': 'device.gbidIsNull' })
            })
          }
        }

      }
    })
  }

  addToPlayList(data) {
    if (!this.deviceExists(data)) {
      let playList = this.state.playList
      if (playList.length >= screenCount[this.state.screenIndex].count) {
        playList.shift()
      }
      playList.push(data)
      this.setState({
        playList
      })
    }
  }

  deviceExists(data) {
    return !(this.state.playList.findIndex(item => item.gbId === data.gbId) === -1)
  }
  deletePlayer(gbId) {
    // 从window.sosList 中剔除GBID
    if (window.sosList) {
      removeArray(window.sosList, gbId)
    }
    let playList = this.state.playList;
    playList.splice(playList.findIndex(item => item.gbId === gbId), 1)
    this.setState({ playList: playList });
  }

  closeAllVideo() {
    this.setState({
      playList: []
    })
  }

  getPlayList() {

  }

  onFullScreen() {
    if (hasFullScreenElement()) {
      exitFullScreen()
    } else {
      setFullScreen(this.videoView);
    }
  }

  render() {

    const playList = this.state.playList
    const vlist = playList.map((item, index) => {
      return <li className={`${item.isSos === true && styles.active} ${styles[screenCount[this.state.screenIndex].listClass]}`} key={item.gbId}>
        {
          item.isSos === true && <div className={styles.sos}>SOS</div>
        }
        <VideoPlayer deletePlayer={this.deletePlayer.bind(this)} device={item} />
      </li>
    })
    for (let i = 0; i < screenCount[this.state.screenIndex].count - this.state.playList.length; i++) {
      vlist.push(<li className={styles[screenCount[this.state.screenIndex].listClass]} key={i}>
        <div className={styles.videoLoading}>{formatMessage({ id: 'liveVideo.no_video' })}</div>
      </li>)
    }


    return (
      <Fragment>
        <Prompt when={true} message={() => {
          this.closeLiveVideo()
        }} />
        <div className='wrapper'>

          {/* 左边的视图列表 */}
          <div className='left-sider'>
            <LeftSider
              // checkable
              // onSelect={this.onSelect.bind(this)}
              onDoubleClick={this.onDoubleClick.bind(this)}
              // onCheck={this.onCheck.bind(this)}
              // onFresh={this.onFresh.bind(this)}
            />

          </div>

          {/* 中间的视图列表 */}
          <div className={styles.videoList}>
            <div className={styles.toolsBar}>
              <ul>
                {
                  screenCount.map((item, index) => {
                    return (
                      <li key={index} className={this.state.screenIndex === index ? styles.active : ''}
                        onClick={this.changeVideoCount.bind(this, index)}>

                        <Tooltip placement="bottom" title={item.title}>
                          <BizIcon className={styles.toolsIcon} type={item.icon} />
                        </Tooltip>
                      </li>
                    )
                  })
                }
              </ul>
              <ul>
                <li>
                  <Tooltip placement="left" title={formatMessage({ id: 'liveVideo.fullscreen' })}>
                    <BizIcon className={styles.toolsIcon} type="icon-quanping" onClick={this.onFullScreen.bind(this)} />
                  </Tooltip>
                </li>
                <li>
                  <Tooltip placement="left" title={formatMessage({ id: 'liveVideo.stop_all_video' })}>
                    <BizIcon className={styles.toolsIcon} type="icon-stop-video" onClick={this.closeAllVideo.bind(this)} />
                  </Tooltip>
                </li>
              </ul>
            </div>
            <div className={styles.videos} ref={node => this.videoView = node}>
              <ul>
                {vlist}
              </ul>
            </div>
          </div>
        </div>
      </Fragment>
    )
  }
}
export default LiveVideo